package beer.coder.walawala.common.logger;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

/**
 * TODO
 *
 * @author amath0312
 * @version 1.0
 * @date 2020-04-19 13:02
 */
public class LogFormatter extends Formatter {

  private static final String format = "[%1$tF %1$tT] [%2$s] %3$s%4$s%n";
  private final Date dat = new Date();

  @Override
  public synchronized String format(LogRecord record) {
    dat.setTime(record.getMillis());

    String message = formatMessage(record);
    String throwable = "";
    if (record.getThrown() != null) {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw);
      pw.println();
      record.getThrown().printStackTrace(pw);
      pw.close();
      throwable = sw.toString();
    }
    return String.format(format,
        new Date(),
        record.getLevel().getName(),
        message,
        throwable);
  }
}
